import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { Svg, RouterView } from 'src/components'
import { getUserInfo } from 'src/redux/action'
import routerData from './routerData'
import { msiteAddress, cityGuess } from "src/api/getData";
import { RECORD_ADDRESS, SAVE_GEOHASH } from 'src/redux/action-type'
import { useLocation } from 'react-router-dom';
import qs from 'query-string'
import { getStore, setStore } from 'src/config/mUtils'
import 'src/style/common.scss';
import './index.scss';

const App = () => {

  const { search, pathname } = useLocation();
  const { geohash: geohashQuery } = qs.parse(search)
  const dispatch = useDispatch();
  console.log(pathname, 'pathname')
  const {
    userInfo,//用户信息
    latitude,//纬度
    longitude,//经度
    geohash,//store中的geohash
  } = useSelector(state => state)

  useEffect(() => {
    // 刷新页面时，获取用户信息，保存到store中
    if (!userInfo) {
      dispatch(getUserInfo())
    }
  }, [dispatch, userInfo])

  useEffect(() => {
    //防止刷新页面时，状态丢失，经度纬度需要重新获取，并存入store，避免重复操作
    if (!latitude && !longitude && geohash) {
      //获取位置信息
      msiteAddress(geohash).then(res => {
        // 记录当前经度纬度进入store
        dispatch({
          type: RECORD_ADDRESS,
          latitude: res.data.latitude,
          longitude: res.data.longitude,
          cityName: res.data.name
        })
      })
    }
  }, [geohash, dispatch])

  useEffect(() => {
    //query中的geohash值改变，更新geohash到store
    if (geohashQuery && geohashQuery !== geohash) {
      setStore('_geohash', geohashQuery)
      dispatch({
        type: SAVE_GEOHASH,
        geohash: geohashQuery
      })
    }
  }, [geohashQuery, dispatch])

  useEffect(() => {
    // home已经获取了当前城市
    if (pathname === '/' || pathname === '/home') return
    // query和store中都没有geohash，取缓存中的，没有则调用接口获得
    if (!geohash && !geohashQuery) {
      const _geohash = getStore('_geohash');
      if (_geohash) {
        dispatch({
          type: SAVE_GEOHASH,
          geohash: _geohash
        })
      } else {
        cityGuess().then(res => {
          let geohashNew = res.data.latitude + ',' + res.data.longitude
          setStore('_geohash', geohashNew)
          dispatch({
            type: SAVE_GEOHASH,
            geohash: geohashNew
          })
        })
      }
    }

  }, [geohash, geohashQuery, dispatch])

  useEffect(() => {
    if (geohash) {
      const _geohash = getStore('_geohash');
      if (geohash !== _geohash) {
        setStore('_geohash', geohash)
      }
    }
  }, [geohash])

  return (
    <div className="page_app">
      <Svg />
      <RouterView data={routerData} />
    </div>
  );
}

export default App;
